// pages/basket/basket.js
const http = require('../../utils/http')
const config = require('../../utils/config')
const api = require('../../utils/extendApi')
const app = require('../../app')
const util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopCartItemDiscounts: [],
    allChecked: false,
    totalMoney: 0,
    finalMoney: 0,
    subtractMoney: 0,
    count: 0,
    selected: [],
    basketIds: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  onShow() {
    util.isLogin()
    this.loadBasketData()
  },

  /***
   * 加载购物车数据
   */
  loadBasketData() {
    var userId = wx.getStorageSync('userId')
    console.log("用户id：", userId)
    var page = this
    var params = {
      url: "/cart?userId=" + userId,
      method: "GET",
      data: {
        status:0
      },
      callBack(res) {
        console.log('res', res);
        if (res && res.length > 0) {
          const resLength = res.length;
          const selectedArray = new Array(resLength).fill(false);
          page.setData({
            shopCartItemDiscounts: res,
            allChecked: false,
            selected: selectedArray
          })
          console.log(page.data.selected)
        } else {
          page.setData({
            shopCartItemDiscounts: []
          })
        }
      },
      errCallBack(res) {}
    }
    http.request(params)
  },

  /***全选 */
  onSelAll() {
    console.log(this.data.selected)
    this.data.allChecked = !this.data.allChecked
    console.log("quanxuan:", this.data.allChecked)
    const resLength = this.data.selected.length;
    if (this.data.allChecked) {
      const selectedArray = new Array(resLength).fill(true);
      this.setData({
        selected: selectedArray
      });
      this.calcul()
    } else {
      const selectedArray = new Array(resLength).fill(false);
      this.setData({
        selected: selectedArray
      });
      this.calcul()
    }
  },

  /***每一项的点击事件 */
  onSelectedItem(e) {
    console.log("点击前：", this.data.selected)
    var scindex = e.currentTarget.dataset.scindex
    this.data.selected[scindex] = !this.data.selected[scindex]
    console.log("点击后：", this.data.selected)
    this.calcul()
  },

  calcul() {
    console.log("calcul", this.data.selected)
    let money = 0;
    for (let i = 0; i < this.data.selected.length; i++) {
      if (this.data.selected[i]) {
        money += this.data.shopCartItemDiscounts[i].goods.price * this.data.shopCartItemDiscounts[i].total;
      }
    }
    this.setData({
      totalMoney: money
    });
    console.log("money", this.data.totalMoney)
  },

  /***
   *  减少数量
   */
  onCountMinus(e) {
    var index = e.currentTarget.dataset.index
    var scindex = e.currentTarget.dataset.scindex
    var shopCartItemDiscounts = this.data.shopCartItemDiscounts // 获取购物车列表
    shopCartItemDiscounts[scindex].total -= 1;

    var page = this
    wx.showLoading()
    var params = {
      url: "/cart",
      method: "PUT",
      data: {
        "id": shopCartItemDiscounts[scindex].id,
        "userId": shopCartItemDiscounts[scindex].userId,
        "parameterId": shopCartItemDiscounts[scindex].parameterId,
        "total": shopCartItemDiscounts[scindex].total,
        "goods": shopCartItemDiscounts[scindex].goods,
        "configuration": shopCartItemDiscounts[scindex].configuration,
        "parameter": shopCartItemDiscounts[scindex].parameter
      },
      callBack(res) {
        page.loadBasketData()
      }
      //   errCallBack(res) {}
    }
    http.request(params)
  },
  /***
   *  增加数量
   */
  onCountPlus(e) {
    var index = e.currentTarget.dataset.index
    var scindex = e.currentTarget.dataset.scindex

    var shopCartItemDiscounts = this.data.shopCartItemDiscounts // 获取购物车列表
    shopCartItemDiscounts[scindex].total += 1;

    var page = this
    wx.showLoading()
    var params = {
      url: "/cart",
      method: "PUT",
      data: {
        "id": shopCartItemDiscounts[scindex].id,
        "userId": shopCartItemDiscounts[scindex].userId,
        "parameterId": shopCartItemDiscounts[scindex].parameterId,
        "total": shopCartItemDiscounts[scindex].total,
        "goods": shopCartItemDiscounts[scindex].goods,
        "configuration": shopCartItemDiscounts[scindex].configuration,
        "parameter": shopCartItemDiscounts[scindex].parameter
      },
      callBack(res) {
        page.loadBasketData()
      }
      //   errCallBack(res) {}
    }
    http.request(params)
  },
  /***
   * 更新购物车的数量
   */
  updateCount(shopCartItemDiscounts, scindex, index, prodCount) {
    var page = this
    wx.showLoading()
    var params = {
      url: "/cart",
      method: "PUT",
      data: {
        count: total,
        prodId: shopCartItemDiscounts[scindex].shopCartItems[index].id,
        skuId: shopCartItemDiscounts[scindex].shopCartItems[index].parameterId,
        shopId: 1
      },
      callBack(res) {
        shopCartItemDiscounts[scindex].shopCartItems[index].total += total
        page.setData({
          shopCartItemDiscounts: shopCartItemDiscounts,
        })
        page.calcul()
        wx.hideLoading()
      },
      errCallBack(res) {}
    }
    http.request(params)
  },


  /**
   * 去结算
   */
  toFirmOrder: function () {
    var basketIds = []
    for (let i = 0; i < this.data.selected.length; i++) {
      if (this.data.selected[i]) {
        basketIds.push(this.data.shopCartItemDiscounts[i].id)
      }
    }
    console.log("basketIds:", basketIds)
    wx.setStorageSync('basketIds', JSON.stringify(basketIds))
    wx.navigateTo({
      url: '../submit-order/submit-order?order-entrytype=2',
    })
  },
  /***
   * 删除商品
   */
  onDelBasket() {
    var basketIds = []
    for (let i = 0; i < this.data.selected.length; i++) {
      if (this.data.selected[i]) {
        basketIds.push(this.data.shopCartItemDiscounts[i].id)
      }
    }
    this.setData({
      basketIds: basketIds
    });
    if (!basketIds.length) {
      api.toast({
        title: "请选择商品"
      })
      return
    } else {
      const page = this
      wx.showModal({
        title: '',
        content: '确认要删除选中的商品吗？',
        confirmColor: '#eb2444',
        complete: (res) => {
          if (res.cancel) {}
          if (res.confirm) {
            console.log("basketids:", page.data.basketIds)
            page.data.basketIds.forEach((id) => {
              console.log("delete" + id)
              var params = {
                url: "/cart?id=" + id,
                method: "DELETE",
                callBack(res) {
                  api.toast({
                    title: "已经删除了"
                  })
                  page.loadBasketData();
                },
                errCallBack(res) {
                  console.error('Error deleting basket item:', res);
                }
              };
              http.request(params);
            });

          }
        }
      })
    }
  },

  onPullDownRefresh() {
    console.log("onPullDownRefresh");
    this.loadBasketData()
  }
})